<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" :size="size" v-if="mode === 'list'">
                <el-row>
                    <el-col>
                        <el-form-item label="" prop="type">
                            <el-select v-model="condition.search.type" placeholder="类型">
                                <el-option label="入群欢迎语"
                                           value="GROUP"></el-option>
                                <el-option label="新客户欢迎语"
                                           value="CUSTOMER"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="showAddDialog">新增配置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-table
            ref="welcomeMsg"
            id="welcomeMsg"
            size="small"
            :data="tableData"
            @selection-change="handleSelectionChange"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column type="selection" width="55" v-if="mode === 'select'"></el-table-column>
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="title"
                label="标题">
            </el-table-column>
            <el-table-column
                prop="type"
                width="100px"
                :formatter="formatType"
                label="类型">
            </el-table-column>
            <el-table-column
                prop="content"
                width="200px"
                label="欢迎语文本内容">
                <template v-slot="scope">
                    <table-popover :text=scope.row.content :length="32"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="attachmentNames"
                label="欢迎语附件">
            </el-table-column>
            <el-table-column
                prop="notify"
                :formatter="formatNotify"
                v-if="mode === 'list'"
                label="是否通知客户群">
            </el-table-column>
            <el-table-column
                prop="templateId"
                label="模版ID">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                v-if="mode === 'list'"
                label="更新时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                v-if="mode === 'list'"
                width="80px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" :size="size">
                <el-form-item label="标题">
                    <el-input v-model="addOrUpdateForm.title"
                              placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select v-model="addOrUpdateForm.type" placeholder="类型">
                        <el-option label="新客户欢迎语" value="CUSTOMER"></el-option>
                        <el-option label="入群欢迎语" value="GROUP"></el-option>
                    </el-select>
                    <div class="form-tips">
                        <el-link type="danger"
                                 size="small"
                                 href="https://developer.work.weixin.qq.com/document/path/96356"
                                 target="_blank">
                            新客户欢迎语配置说明
                        </el-link>
                        <br/>
                        <el-link type="danger"
                                 size="small"
                                 href="https://developer.work.weixin.qq.com/document/path/96357"
                                 target="_blank">
                            入群欢迎语配置说明
                        </el-link>
                    </div>
                </el-form-item>
                <el-form-item label="欢迎语文本内容">
                    <el-input v-model="addOrUpdateForm.content" type="textarea" :autosize="{ minRows: 2}"
                              placeholder="欢迎语文本内容"></el-input>
                    <div class="form-tips">支持a标签，支持nickname占位符</div>
                </el-form-item>
                <el-form-item label="是否通知客户群" v-if="addOrUpdateForm.type === 'GROUP'">
                    <el-switch v-model="addOrUpdateForm.notify"></el-switch>
                </el-form-item>
                <el-form-item label="添加附件">
                    <el-button @click="selectMaterialDialogVisible = true" size="mini" type="success">
                        添加素材
                    </el-button>
                    <div v-if="selectedMaterials.length > 0" style="margin-top: 10px"
                         v-for="(item, index) in this.selectedMaterials" :key="index">
                        <material-show :info="item"></material-show>
                        <div>{{ item.title }}</div>
                        <el-popconfirm
                            @confirm="handleConfirm(index)"
                            confirm-button-text='好的'
                            cancel-button-text='不用了'
                            icon="el-icon-info"
                            icon-color="red"
                            title="这是一段内容确定删除吗？">
                            <el-button size="mini" slot="reference">删除</el-button>
                        </el-popconfirm>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :size="size" @click="addOrUpdateDialogVisible = false">取 消</el-button>
                <el-button :size="size" @click="addOrUpdateConfirm" type="primary">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择素材" width="70%" :visible.sync="selectMaterialDialogVisible" append-to-body>
            <work-material ref="materialSelect" size="small" @select="onSelectMaterial" mode="select"
                           :work-corp-id="workCorpId"></work-material>
            <div slot="footer" class="dialog-footer"></div>
        </el-dialog>
    </div>
</template>

<script>
import {addWorkWelcomeMsg, deleteWorkWelcomeMsg, getWorkWelcomeMsgByPage, updateWorkWelcomeMsg} from '@/api/api'
import WorkMaterial from "@/component/workwx/WorkMaterial";
import TablePopover from "@/component/single/TablePopover";
import MaterialShow from "@/component/workwx/MaterialShow";

export default {
    name: "WorkWelcomeMsg",
    components: {WorkMaterial, TablePopover, MaterialShow},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            welcomeMsgSelected: [],

            selectMaterialDialogVisible: false,
            selectedMaterials: [],
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        size: {
            type: String,
            default: 'small'
        },
        mode: {
            type: String,
            default: 'list'
        },
        // 选中的行
        selected: {
            type: Array,
            default: () => []
        },
        workCorpId: String
    },
    watch: {
        selected: function (val, oldVal) {
            this.selected = val;
            this.setChecked();
        }
    },
    methods: {
        handleSelectionChange(val) {
            this.welcomeMsgSelected = val;
        },
        onSelectMaterial(row) {
            this.selectedMaterials.push(row);
            this.selectMaterialDialogVisible = false;
            this.addOrUpdateForm.attachments = this.selectedMaterials;
        },
        handleConfirm(index) {
            this.selectedMaterials.splice(index, 1);
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatType: function (row, column, cellValue) {
            if (!cellValue) {
                return;
            }
            if (cellValue == 'GROUP') {
                return "入群欢迎语";
            } else if (cellValue == 'CUSTOMER') {
                return "新客户欢迎语";
            } else {
                return "未知";
            }
        },
        formatNotify: function (row, column, cellValue) {
            if (cellValue === undefined) {
                return '';
            }
            if (cellValue == '0') {
                return "不通知";
            } else if (cellValue == '1') {
                return "通知";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            this.addOrUpdateForm.workCorpId = this.workCorpId;
            this.$set(this.addOrUpdateForm, "notify", false)
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
            this.selectedMaterials = row.attachments;
            if (!this.selectedMaterials) {
                this.selectedMaterials = [];
            }
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#welcomeMsg', '数据.xlsx');
        },
        add: function () {
            addWorkWelcomeMsg(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateWorkWelcomeMsg(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteWorkWelcomeMsg({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            if (this.workCorpId) {
                this.condition.search.workCorpId = this.workCorpId;
            }
            getWorkWelcomeMsgByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                this.setChecked();
            });
        },
        // 设置多选
        setChecked: function () {
            this.$refs.welcomeMsg.clearSelection();
            this.selected.forEach(item => {
                this.$nextTick(() => {
                    this.tableData.find(obj => {
                        if (item.id === obj.id) {
                            this.$refs.welcomeMsg.toggleRowSelection(obj, true)
                        }
                    })
                })
            })
        }
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
